package com.aaa.jx.controller;

import com.aaa.jx.entity.TabUser;
import com.aaa.jx.service.TabUserService;
import com.aaa.jx.service.impl.TabUserServiceImpl;
import com.util.LayData;
import com.util.PrintJsonData;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    TabUserService tabUserService = new TabUserServiceImpl();
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        LayData layData = new LayData();
        TabUser tabUser=new TabUser();
        tabUser.setUsername(username);
        tabUser.setPassword(password);
        List<TabUser> tabUsers = tabUserService.queryAll(tabUser);
        if (tabUsers.isEmpty()){
            layData.setData(false);
            PrintJsonData.printData(resp,layData);
        }else {
            Map<String,Object> map=new HashMap<>();
            map.put("username",username);
            map.put("password",password);
            for (TabUser user : tabUsers) {
                map.put("id",user.getId());
            }
            HttpSession session=req.getSession(true);
            session.setAttribute("user",map);
            layData.setData(true);
            PrintJsonData.printData(resp,layData);
        }
    }
}
